import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/empty_widget.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/goods/goods_select_condition_widget.dart';
import 'package:gzmall_app/model/brand.dart';
import 'package:gzmall_app/model/product.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import './goods_list_item_widget.dart';
import './goods_details_page.dart';
import 'package:flutter/widgets.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';

class GoodsListWidget extends StatefulWidget {
  int categoryId = 0;
  String categoryName;
  String searchKey;
  int level;

  GoodsListWidget({
    this.categoryId,
    this.categoryName,
    this.searchKey,
    this.level,
  });

  @override
  State<StatefulWidget> createState() {
    return new GoodsListWidgetState(
        categoryId: categoryId,
        categoryName: categoryName,
        searchKey: searchKey,
        level: level);
  }
}

class GoodsListWidgetState extends State<GoodsListWidget>
    with SingleTickerProviderStateMixin {
  double _topPadding;

  double _itemWidth;

  int categoryId = 0;
  String categoryName;
  String searchKey;
  int level;
  List<Product> spus = [];
  List<Brand> _brands = [];

  bool isRow = false;

  int _functionType1 = 1, _functionType2 = 1, _sortState = 0;
  bool _isNew = false;
  int _brandId = -1;
  int _showBrandId = -1;

  AnimationController controller;
  Animation<double> animation;

  int _curPage = 1;
  RefreshListView _refreshListView;
  String _emptyTips = '商品在马不停蹄赶来';
  bool _showEmpty = false;

  GoodsListWidgetState({
    this.categoryId,
    this.categoryName,
    this.searchKey,
    this.level,
  });

  @override
  void initState() {
    super.initState();
    _getData(1);

    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 100));
    animation = Tween(begin: 50.0, end: 280.0).animate(controller);
  }

  _getData(int page) {
    if (categoryId != null && categoryId > 0) {
      _getCategoryChildren(categoryId, page);
      _getBrand();
    } else if (searchKey != null && searchKey.isNotEmpty) {
      _getSearchProduct(searchKey, page);
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
    var size = MediaQuery.of(context).size;
    _itemWidth = (size.width - 12) / 2;
  }

  Widget _buildGoodList(BuildContext context) {
    Widget list;
    if (isRow) {
      list = _buildList();
    } else {
      list = _buildGirdList();
    }
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: list,
      emptyTips: _emptyTips,
      showEmpty: _showEmpty,
      onReload: () {
        _getData(1);
      },
    );
    return _refreshListView;
  }

  Widget _buildGirdList() {
    List<Widget> spuList = spus
        .map((item) => new InkWell(
              child: new GoodsListItemWidget(item, _itemWidth),
              onTap: () {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new GoodsDetailsPage(productId: item.id);
                }));
              },
            ))
        .toList();
    return GridView.count(
      shrinkWrap: true,
      padding: const EdgeInsets.only(left: 4.0, right: 4.0, top: 4.0),
      crossAxisSpacing: 4.0,
      mainAxisSpacing: 4.0,
      controller: new ScrollController(keepScrollOffset: false),
      crossAxisCount: 2,
      childAspectRatio: 0.65,
      children: spuList,
    );
  }

  Widget _buildList() {
    List<Widget> spuList = spus
        .map((item) => new InkWell(
              child: Container(
                color: Colors.white,
                margin: const EdgeInsets.only(bottom: 1.0),
                padding: const EdgeInsets.only(
                    left: 10.0, right: 10.0, top: 10.0, bottom: 10.0),
                child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      CachedNetworkImage(
                        imageUrl: item.avatar,
                        fit: BoxFit.fill,
                        width: 120.0,
                        height: 120.0,
                      ),
                      Expanded(
                        child: Container(
                          height: 120.0,
                          margin: const EdgeInsets.only(left: 10.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  item.name,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: 14.0,
                                      color: ColorCommon.black1),
                                ),
                              ),
                              Container(
                                padding: const EdgeInsets.only(top: 4.0),
                                child: Row(children: <Widget>[
                                  item.directSale != null && item.directSale
                                      ? Padding(
                                          padding:
                                              const EdgeInsets.only(right: 4.0),
                                          child: _getTagView(
                                              "自营",
                                              Colors.white,
                                              ColorCommon.primaryColor,
                                              ColorCommon.primaryColor))
                                      : Container(),
                                  item.promotion != null && item.promotion
                                      ? Padding(
                                          padding:
                                              const EdgeInsets.only(right: 4.0),
                                          child: _getTagView(
                                              "促销价",
                                              Colors.white,
                                              ColorCommon.primaryColor,
                                              ColorCommon.primaryColor),
                                        )
                                      : Container(),
                                  Expanded(
                                    child: Text(
                                      "98.0%好评",
                                      style: TextStyle(
                                          fontSize: 14.0,
                                          color: ColorCommon.grey8),
                                    ),
                                  ),
                                ]),
                              ),
                              Container(
                                padding: const EdgeInsets.only(top: 4.0),
                                child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: <Widget>[
                                      Text(
                                        "¥" +
                                            (item.promotion != null &&
                                                    item.promotion
                                                ? (item.lowPromotionPrice ??
                                                    "0.0")
                                                : (item.lowSalePrice ?? "0.0")),
                                        style: TextStyle(
                                            fontSize: 18.0,
                                            color: ColorCommon.primaryColor),
                                      ),
                                      item.promotion != null && item.promotion
                                          ? Expanded(
                                              child: Padding(
                                                padding: const EdgeInsets.only(
                                                    left: 4.0),
                                                child: Text(
                                                  "¥" +
                                                      (item.lowSalePrice ??
                                                          "0.0"),
                                                  style: TextStyle(
                                                    fontSize: 14.0,
                                                    color: ColorCommon.grey8,
                                                    decoration: TextDecoration
                                                        .lineThrough,
                                                    decorationStyle:
                                                        TextDecorationStyle
                                                            .solid,
                                                  ),
                                                ),
                                              ),
                                            )
                                          : Container(),
                                    ]),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ]),
              ),
              onTap: () {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new GoodsDetailsPage(productId: item.id);
                }));
              },
            ))
        .toList();
    return ListView(
      padding: EdgeInsets.only(top: 0.0),
      children: spuList,
    );
  }

  @override
  Widget build(BuildContext context) {
    init();
    return Scaffold(
        body: Container(
      color: ColorCommon.grey2,
      child: Column(children: <Widget>[
        _createSearchAppBar(),
        _createControlBar1(),
        // _createControlBar2(),
        Expanded(
          child: Stack(
            children: <Widget>[
              _buildGoodList(context),
              _functionType2 == 2 || _functionType2 == 3
                  ? Positioned(
                      left: 0.0,
                      right: 0.0,
                      top: 0.0,
                      bottom: 0.0,
                      child: GoodsSelectConditionWidget(
                        brands: _brands,
                        curBrandId: _showBrandId,
                        animation: animation,
                        onReset: () {
                          new Future.delayed(Duration.zero, () {
                            if (!mounted) return;
                            setState(() {
                              switch (_functionType2) {
                                case 2:
                                  _functionType2 = 1;
                                  _brandId = -1;
                                  _showBrandId = -1;
                                  _getData(1);
                                  break;
                                default:
                              }
                            });
                          });
                        },
                        onConfirm: (id) {
                          new Future.delayed(Duration.zero, () {
                            if (!mounted) return;
                            setState(() {
                              switch (_functionType2) {
                                case 2:
                                  _functionType2 = 1;
                                  _brandId = id;
                                  _showBrandId = id;
                                  _getData(1);
                                  break;
                                default:
                              }
                            });
                          });
                        },
                        onSelect: (id) {
                          new Future.delayed(Duration.zero, () {
                            if (!mounted) return;
                            setState(() {
                              switch (_functionType2) {
                                case 2:
                                  _functionType2 = 2;
                                  _showBrandId = id;
                                  break;
                                default:
                              }
                            });
                          });
                        },
                        onDismiss: () {
                          new Future.delayed(Duration.zero, () {
                            if (!mounted) return;
                            setState(() {
                              switch (_functionType2) {
                                case 2:
                                  _functionType2 = 1;
                                  _showBrandId = _brandId;
                                  break;
                                default:
                              }
                            });
                          });
                        },
                      ),
                    )
                  : Container(),
            ],
          ),
        ),
      ]),
    ));
  }

  _createSearchAppBar() {
    return new Container(
      padding: EdgeInsets.fromLTRB(10.0, _topPadding + 10.0, 10.0, 10.0),
      color: const Color(0xFFE44949),
      child: new Row(
        children: <Widget>[
          GestureDetector(
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
            ),
            onTap: () {
              Navigator.of(context).pop();
            },
          ),
          new Expanded(
            child: new GestureDetector(
              child: new Container(
                height: 28.0,
                padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                margin: const EdgeInsets.only(left: 10.0, right: 10.0),
                decoration: new BoxDecoration(
                    color: ColorCommon.translucent1,
                    borderRadius: new BorderRadius.circular(100.0)),
                child: new Row(
                  children: <Widget>[
                    new Padding(
                      padding: const EdgeInsets.only(right: 8.0),
                      child: new Image.asset(
                        'images/search.png',
                        width: 16.0,
                        height: 16.0,
                      ),
                    ),
                    new Text(
                      categoryName != null && categoryName.isNotEmpty
                          ? categoryName
                          : searchKey != null && searchKey.isNotEmpty
                              ? searchKey
                              : "",
                      style: new TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
              onTap: () {
                Navigator.of(context).pushNamed('/search_goods_page');
              },
            ),
          ),
          GestureDetector(
            child: Icon(
              Icons.menu,
              color: Colors.white,
            ),
            onTap: () {
              if (!mounted) return;
              setState(() {
                isRow = !isRow;
              });
            },
          ),
        ],
      ),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text(
        categoryName != null && categoryName.isNotEmpty
            ? categoryName
            : searchKey != null && searchKey.isNotEmpty ? searchKey : "",
      ),
      centerTitle: true,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[
        GestureDetector(
          child: Padding(
            padding: const EdgeInsets.only(right: 8.0),
            child: Icon(Icons.search),
          ),
          onTap: () {},
        ),
        GestureDetector(
          child: Padding(
            padding: const EdgeInsets.only(right: 8.0),
            child: Icon(Icons.menu),
          ),
          onTap: () {},
        ),
      ],
    );
  }

  _createControlBar1() {
    return Container(
        height: 45.0,
        color: Colors.white,
        child: Row(
          children: <Widget>[
            _getBarFunction1Btn("综合", () {
              if (!mounted) return;
              setState(() {
                _functionType1 = 1;
                _sortState = 0;
                _getData(1);
              });
            }, Container(),
                _functionType1 == 1 ? ColorCommon.primaryColor : ColorCommon.black1),
            _getBarFunction1Btn("销量", () {
              if (!mounted) return;
              setState(() {
                _functionType1 = 2;
                _sortState = 0;
                _getData(1);
              });
            }, Container(),
                _functionType1 == 2 ? ColorCommon.primaryColor : ColorCommon.black1),
            _getBarFunction1Btn("价格", () {
              if (!mounted) return;
              setState(() {
                _functionType1 = 3;
                _sortState = _sortState > 0 ? (_sortState == 1 ? 2 : 1) : 1;
                _getData(1);
              });
            },
                Image.asset(
                  _sortState > 0
                      ? (_sortState == 1
                          ? 'images/sort_1.png'
                          : 'images/sort_2.png')
                      : 'images/sort.png',
                  width: 12.0,
                  height: 12.0,
                ),
                _functionType1 == 3 ? ColorCommon.primaryColor : ColorCommon.black1),
            // _getBarFunction1Btn("逛品牌", () {
            //   if (!mounted) return;
            //   setState(() {
            //     _functionType1 = 4;
            //     _sortState = 0;
            //     _getData();
            //   });
            // }, Container(),
            //     _functionType1 == 4 ? ColorCommon.primaryColor : ColorCommon.black1),
            // _getBarFunction1Btn("筛选", () {
            //   if (!mounted) return;
            //   setState(() {
            //     _functionType1 = 5;
            //     _sortState = 0;
            //   });
            // },
            //     Image.asset(
            //       _functionType1 == 5
            //           ? 'images/sift_u.png'
            //           : 'images/sift_n.png',
            //       width: 10.0,
            //       height: 10.0,
            //     ),
            //     _functionType1 == 5 ? ColorCommon.primaryColor : ColorCommon.black1),
            categoryId != null && categoryId > 0
                ? _getBarFunction1Btn("品牌", () {
                    if (!mounted) return;
                    setState(() {
                      _functionType2 = _functionType2 == 2 ? 1 : 2;
                      if (_functionType2 == 2) {
                        controller.reset();
                        controller.forward();
                      }
                    });
                  },
                    Container(),
                    _functionType2 == 2 || _brandId != null && _brandId > 0
                        ? ColorCommon.primaryColor
                        : ColorCommon.black1)
                : Container(),
            _getBarFunction1Btn("最新", () {
              if (!mounted) return;
              setState(() {
                _isNew = !_isNew;
                _getData(1);
              });
            }, Container(), _isNew ? ColorCommon.primaryColor : ColorCommon.black1),
          ],
        ));
  }

  _createControlBar2() {
    return Container(
      color: Colors.white,
      height: 45.0,
      margin: const EdgeInsets.only(top: 1.0, bottom: 1.0),
      padding: const EdgeInsets.only(left: 20.0, right: 20.0),
      child: Row(
        children: <Widget>[
          _getBarFunction2Btn("最新产品", () {
            if (!mounted) return;
            setState(() {
              _isNew = !_isNew;
              _getData(1);
            });
          }, 1, Container()),
          _getBarFunction2Btn("品牌", () {
            if (!mounted) return;
            setState(() {
              _functionType2 = _functionType2 == 2 ? 1 : 2;
              if (_functionType2 == 2) {
                controller.reset();
                controller.forward();
              }
            });
          },
              2,
              Icon(
                Icons.arrow_drop_down,
                size: 15.0,
                color:
                    _functionType2 == 2 ? ColorCommon.primaryColor : ColorCommon.grey6,
              )),
          _getBarFunction2Btn("分类", () {
            if (!mounted) return;
            setState(() {
              _functionType2 = _functionType2 == 3 ? 1 : 3;
              if (_functionType2 == 3) {
                controller.reset();
                controller.forward();
              }
            });
          },
              3,
              Icon(
                Icons.arrow_drop_down,
                size: 18.0,
                color:
                    _functionType2 == 3 ? ColorCommon.primaryColor : ColorCommon.grey6,
              )),
        ],
      ),
    );
  }

  _getBarFunction1Btn(
      String text, Function onTap, Widget rightWidget, Color fontColor) {
    return Expanded(
        child: InkWell(
            onTap: onTap,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  text,
                  style: TextStyle(fontSize: 15.0, color: fontColor),
                  textAlign: TextAlign.center,
                ),
                rightWidget,
              ],
            )));
  }

  _getBarFunction2Btn(
      String text, Function onTap, int type, Widget rightWidget) {
    Color _bgColor = ColorCommon.grey2,
        _borderColor = ColorCommon.grey2,
        _fontColor = ColorCommon.grey6;
    switch (type) {
      case 1:
        if (_isNew) {
          _bgColor = Colors.white;
          _borderColor = ColorCommon.primaryColor;
          _fontColor = ColorCommon.primaryColor;
        }
        break;
      case 2:
        if (_functionType2 == 2) {
          _bgColor = Colors.white;
          _borderColor = Colors.white;
          _fontColor = ColorCommon.primaryColor;
        }
        break;
      case 3:
        if (_functionType2 == 3) {
          _bgColor = Colors.white;
          _borderColor = Colors.white;
          _fontColor = ColorCommon.primaryColor;
        }
        break;
    }
    return Expanded(
        child: InkWell(
            onTap: onTap,
            child: Container(
              height: 25.0,
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 10.0, right: 10.0),
              decoration: BoxDecoration(
                  color: _bgColor,
                  border: Border.all(color: _borderColor),
                  borderRadius: BorderRadius.all(Radius.circular(100.0))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    text,
                    style: TextStyle(fontSize: 15.0, color: _fontColor),
                    textAlign: TextAlign.center,
                  ),
                  rightWidget,
                ],
              ),
            )));
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 4.0, right: 4.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 13.0, color: textColor),
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getData(1);
    } else {
      _getData(_curPage + 1);
    }
  }

  _getCategoryChildren(int id, int page) async {
    if (id != null && id > 0) {
      bool isGetNew = page == 1;
      Map<String, String> params = {
        "shop_category_id": id.toString(),
        "page": page.toString()
      };
      if (_functionType1 == 2) {
        // 销量排序
        params["sales_volumn"] = "1";
      } else if (_functionType1 == 3 && _sortState == 1) {
        // 价格排序-正序
        params["sales_price"] = "ASC";
      } else if (_functionType1 == 3 && _sortState == 2) {
        // 价格排序-倒序
        params["sales_price"] = "DESC";
      }
      // 品牌选择
      if (_brandId != null && _brandId > 0) {
        params["brand_id"] = _brandId.toString();
      }
      // 是否最新
      params["newest"] = _isNew.toString();
      NetUtil.get(
          context,
          Api.spus,
          (data, message) {
            if (!mounted) return;
            _curPage = page;
            var _dataList = (data as List)
                ?.map((e) => e == null ? null : Product.fromJson(e))
                ?.toList();
            setState(() {
              _showEmpty =
                  isGetNew && (_dataList == null || _dataList.length <= 0);
              _emptyTips = '没有符合条件的商品';
              if (isGetNew) {
                spus = _dataList;
              } else {
                spus.addAll(_dataList);
              }
            });
            if (_refreshListView != null) {
              _refreshListView.refreshCompleted(isGetNew,
                  hasMore:
                      _dataList != null && _dataList.length >= Api.pageSize);
            }
          },
          params: params,
          errorCallBack: (e) {
            setState(() {
              _showEmpty = isGetNew && (spus == null || spus.length <= 0);
              _emptyTips = '没有符合条件的商品';
            });
            if (_refreshListView != null) {
              _refreshListView.refreshCompleted(isGetNew);
            }
          });
    }
  }

  _getSearchProduct(String key, int page) async {
    if (key != null) {
      bool isGetNew = page == 1;
      Map<String, String> params = {"search_key": key, "page": page.toString()};
      if (_functionType1 == 2) {
        // 销量排序
        params["sales_volumn"] = "1";
      } else if (_functionType1 == 3 && _sortState == 1) {
        // 价格排序-正序
        params["sales_price"] = "ASC";
      } else if (_functionType1 == 3 && _sortState == 2) {
        // 价格排序-倒序
        params["sales_price"] = "DESC";
      }
      // 品牌选择
      if (_brandId != null && _brandId > 0) {
        params["brand_id"] = _brandId.toString();
      }
      // 是否最新
      params["newest"] = _isNew.toString();
      NetUtil.get(
          context,
          Api.pagesSearch,
          (data, message) {
            if (!mounted) return;
            _curPage = page;
            var _dataList = (data as List)
                ?.map((e) => e == null ? null : Product.fromJson(e))
                ?.toList();
            setState(() {
              _showEmpty =
                  isGetNew && (_dataList == null || _dataList.length <= 0);
              _emptyTips = '没有符合条件的商品';
              if (isGetNew) {
                spus = _dataList;
              } else {
                spus.addAll(_dataList);
              }
            });
            if (_refreshListView != null) {
              _refreshListView.refreshCompleted(isGetNew,
                  hasMore:
                      _dataList != null && _dataList.length >= Api.pageSize);
            }
          },
          params: params,
          errorCallBack: (e) {
            setState(() {
              _showEmpty = isGetNew && (spus == null || spus.length <= 0);
              _emptyTips = '没有符合条件的商品';
            });
            if (_refreshListView != null) {
              _refreshListView.refreshCompleted(isGetNew);
            }
          });
    }
  }

  _getBrand() {
    Map<String, String> params = {
      "shop_category_id": this.categoryId.toString(),
      "level": this.level.toString(),
    };
    NetUtil.get(context, Api.brands, (data, message) {
      if (!mounted) return;
      setState(() {
        _brands = (data as List)
            ?.map((e) => e == null ? null : Brand.fromJson(e))
            ?.toList();
      });
    }, params: params);
  }
}
